package com.client.job.runJob;

import java.lang.reflect.Method;

import com.client.job.core.model.MJob;
import com.client.job.core.model.MJobInstance;
import com.client.job.utils.MJobUtils;
import com.client.job.utils.SpringUtil;
import lombok.extern.slf4j.Slf4j;


/**
 * Job分片策略
 *
 * @author mengxiangzhong
 * @des
 * @date 2021年9月2日
 */
@Slf4j
public class JobBurstPolicy {

    /**
     * 反射执行方法注解
     *
     * @throws ClassNotFoundException
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    public static void callBack(MJob mJob, MJobInstance mJobInstance) throws Exception {
        //类名、方法名
        String className = mJob.getToLong().substring(0, mJob.getToLong().lastIndexOf("."));
        String methodName = mJob.getToLong().substring(mJob.getToLong().lastIndexOf(".") + 1,
                mJob.getToLong().length());
        String beanName = className.substring(className.lastIndexOf(".") + 1, className.length());
        beanName = beanName.substring(0, 1).toLowerCase() + beanName.substring(1);
        //获取Job的执行策略
        MJobUtils.analysisParams(mJob, mJobInstance);
        //反射执行Spring方法
        try {
            excuteJob(beanName, methodName, mJob);
        } catch (Exception e) {
            log.error("该Job为普通的类");
            //反射执行普通方法
            Class cz = Class.forName(className);
            Method method = cz.getMethod(methodName, MJob.class);
            method.invoke(cz.newInstance(), mJob);
        }
    }


    /**
     * 反射执行Spring方法
     *
     * @param className
     * @param methodName
     * @param mjob
     */
    private static void excuteJob(String className, String methodName, MJob mjob) throws Exception {
        Object proxyObject = SpringUtil.getBean(className);
        if (proxyObject == null) {
            throw new RuntimeException("class can not find : " + className);
        }
        Method method = SpringUtil.getMethod(proxyObject.getClass(), methodName);
        method.invoke(proxyObject, mjob);
    }

}
